import os
import time
import numpy as np
import pickle
import struct
import re
import cv2
from tqdm import tqdm
import imageio
import json

import random
import copy
from PIL import Image, ImageColor, ImageFont, ImageDraw, ImageFilter

# from tool import utils # export PYTHONPATH=$PYTHONPATH:`pwd`


def image_enhance_for_cv_image(cv_image ):
    """
        获得灰度图像掩码
    """
    ratio = np.random.randint(7,12) * 0.1
    if ratio > 1:
        interplatation =  cv2.INTER_CUBIC
    else:
        interplatation =  cv2.INTER_AREA
    array = cv2.resize(cv_image, (int(cv_image.shape[1] *ratio) , int(cv_image.shape[0] *ratio)), None,0,0,interplatation)

    # array_mask= cv2.bitwise_not(array)
    # array_mask = cv2.threshold(array, 180, 255,cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
    array_mask = cv2.threshold(array, 254, 255,cv2.THRESH_BINARY_INV)[1]

    array_image = cv2.bitwise_not(array_mask)
    # array_image = cv2.cvtColor(array_image, cv2.COLOR_GRAY2RGB)
    return array_image, array_mask


def get_text_label_info(txt_img, diff_height=0):

    image_array = np.frombuffer(txt_img.tobytes(), dtype=np.uint8)
    image_array = image_array.reshape((txt_img.size[1], txt_img.size[0], 4))
    image_array = image_array[:,:,:3]

    
    gray_image = cv2.cvtColor(image_array, cv2.COLOR_RGB2GRAY)
    bin_image = cv2.threshold(gray_image, 1, 255, cv2.THRESH_BINARY)[1]
    # cv2.imwrite("a.jpg",bin_image )
    col_sum = np.sum(bin_image, axis=0)

    col_sum[col_sum<=1] = 0
    col_sum[col_sum>1] = 1
    
    col_sum = np.array(col_sum, dtype=np.int32)
    start_end_list = []
    start = 0
    end = 0

    for i in range(1, len(col_sum)):
        if col_sum[i] - col_sum[i-1] > 0:
            start = i
        elif col_sum[i] - col_sum[i-1] < 0:
            end = i
            start_end_list.append([start, end])
        elif i == len(col_sum)-1 and col_sum[i] - col_sum[i-1] == 0:
            end = i
            start_end_list.append([start, end])


    pts =  []
    for s,e in start_end_list:
        crop_img = bin_image[:, s:e]
        row_sum = np.sum(crop_img, axis=1)
        row_index = np.where(row_sum>0)[0]
        row_start = row_index[0]
        row_end = row_index[-1]

        pts.append([s, row_start + diff_height, e-s, row_end-row_start])
    # print(pts)
    return pts


